/**
   BasicHTTPClient.ino

    Created on: 24.05.2015

*/

#include <Arduino.h>
#include <ESP8266WiFi.h>
#include <ESP8266WiFiMulti.h>
#include <ESP8266HTTPClient.h>
#include <WiFiClient.h>
#include "myhttp.h"
#include "protocol.h"
#include <ArduinoJson.h>
#include "power.h"
#include "lcd.h"
#include "adc.h"

ESP8266WiFiMulti WiFiMulti;
WiFiClient client;
HTTPClient http;

HTTPClient &GetHttpHan(void)
{
  return http;
}

WiFiClient &GetWifiHan(void)
{
  return client;
}

void UartPrintf (const char *fmt, ...) 
{
  #define USART_SEND_MAXLEN  100  
	char buffer[USART_SEND_MAXLEN+1];
	int sendLen = 0; 

	va_list arg_ptr; 
	va_start(arg_ptr, fmt);   
	sendLen = vsnprintf(buffer, USART_SEND_MAXLEN+1, fmt, arg_ptr); 
	va_end(arg_ptr);
    if (sendLen > 0) {
        Serial.println(buffer);
    }
}

void setup() {

  Serial.begin(115200);
  // Serial.setDebugOutput(true);
  Serial.println();
  for (uint8_t t = 4; t > 0; t--) {
    Serial.printf("[SETUP] WAIT %d...\n", t);
    Serial.flush();
    delay(1000);
  }

  WiFi.mode(WIFI_STA);
  WiFiMulti.addAP("lx1314", "l123456789+");
  // MyHttpinit();
  ProtoColInit(ProtocolGetCtrl(), HttpCmdSend, UartPrintf);
  PowerInit();
  LcdInit();
  AdcInit();
}

int IsWiFiRun(void)
{
  if ((WiFiMulti.run() == WL_CONNECTED)) {
    return 1;
  }
  return 0;
}

unsigned int tick = 0;
void loop() {
  tick++;
  // wait for WiFi connection
  AdcTask(tick);
  // HttpTask(tick);
  PowerTask(tick);
  ProtoColTask(ProtocolGetCtrl());
  LcdTask(tick);
  delay(1);
}
